package com.chuantou.yuba.ui.widget;

import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.FishingShopDataTO;
import com.chuantou.yuba.api.to.FishingShopTO;
import com.chuantou.yuba.ui.FishingShopDetailActivity;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.ui.widget.stickylistheaders.StickyListHeadersAdapter;
import com.chuantou.yuba.ui.widget.stickylistheaders.StickyListHeadersListView;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.ViewHolder;

public class FishingShopPopup extends PopupWindow {
	private Context mContext;
	private List<FishingShopTO> mShops;
	private View mContentView;
	private StickyListHeadersListView mListView;
	private LoadingView mLoadingView;
	private FishingShopAdapter mAdapter;
	private int[] mSectionPositions;
	private String[] mSectionText;

	public FishingShopPopup(Context context, List<FishingShopTO> shops) {
		this.mContext = context;
		this.mShops = shops;
		mContentView = View.inflate(mContext, R.layout.fishing_shop_popup, null);
		mListView = (StickyListHeadersListView) mContentView.findViewById(android.R.id.list);
		mAdapter = new FishingShopAdapter();
		mListView.setAdapter(mAdapter);
		mLoadingView = (LoadingView) mContentView.findViewById(android.R.id.empty);
		mLoadingView.setStyle(Style.LOADING, null);
		mLoadingView.setOnRetryListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mLoadingView.setStyle(Style.LOADING, null);
				requestFromNetwork();
			}
		});
		mListView.setEmptyView(mLoadingView);
		if (mShops != null && !mShops.isEmpty()) {
			sort(mShops);
			mAdapter.notifyDataSetChanged();
		} else {
			requestFromNetwork();
		}
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Object obj = parent.getItemAtPosition(position);
				if (obj != null && obj instanceof FishingShopTO) {
					FishingShopTO shopTO = (FishingShopTO) obj;
					Intent intent = new Intent(mContext, FishingShopDetailActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra(Constants.EXTRA_DATA, shopTO.getId());
					mContext.startActivity(intent);
					dismiss();
				}
			}
		});
		setContentView(mContentView);
		setHeight(FrameLayout.LayoutParams.MATCH_PARENT);
		setWidth(FrameLayout.LayoutParams.MATCH_PARENT);
		setFocusable(true);
		setAnimationStyle(R.style.popup_style);
		ColorDrawable drawable = new ColorDrawable(mContext.getResources().getColor(R.color.translucence));
		setBackgroundDrawable(drawable);
	}

	private void sort(List<FishingShopTO> list) {
		ArrayList<String> sectionTexts = new ArrayList<String>();
		ArrayList<Integer> sectionPositions = new ArrayList<Integer>();
		if (list != null && !list.isEmpty()) {
			Collections.sort(list, NameComparator.getInstance());
			int listPos = 0;
			for (FishingShopTO shop : list) {
				String firstSpell = shop.getLetter();
				if (!sectionTexts.contains(firstSpell)) {
					sectionTexts.add(firstSpell);
					sectionPositions.add(listPos);
				}
				listPos++;
			}
			mSectionText = sectionTexts.toArray(new String[sectionTexts.size()]);
			int[] sectionPositionArray = new int[sectionPositions.size()];
			for (int i = 0; i < sectionPositionArray.length; i++) {
				sectionPositionArray[i] = sectionPositions.get(i);
			}
			mSectionPositions = sectionPositionArray;
		} else {
			mSectionPositions = new int[0];
			mSectionText = new String[0];
		}
	}

	private void requestFromNetwork() {
		String url = UriHelper.getNearFishingShopUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_DISTANCE, String.valueOf("0"));
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(10000));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		// 品牌商
		params.put(UriHelper.PARAMS_TYPE, "2");
		GsonRequest<FishingShopDataTO> request = new GsonRequest<FishingShopDataTO>(Method.POST, url, new Listener<FishingShopDataTO>() {

			@Override
			public void onResponse(FishingShopDataTO response) {
				if (isShowing()) {
					List<FishingShopTO> list = response.getShops();
					if (list != null && !list.isEmpty()) {
						sort(list);
						mShops = list;
						mAdapter.notifyDataSetChanged();
					} else {
						mLoadingView.setStyle(Style.EMPTY, mContext.getString(R.string.no_content));
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (isShowing()) {
					mLoadingView.setStyle(Style.ERROR, null);
				}
			}
		}, params, FishingShopDataTO.class);
		RequestManager.startRequest(mContext, request);
	}

	// 名字正序
	static final class NameComparator implements Comparator<FishingShopTO> {

		static Comparator<FishingShopTO> instance;

		private static RuleBasedCollator collator;

		public static Comparator<FishingShopTO> getInstance() {
			if (instance == null) {
				instance = new NameComparator();
				collator = (RuleBasedCollator) Collator.getInstance(java.util.Locale.CHINA);
			}
			return instance;
		}

		private NameComparator() {

		}

		@Override
		public int compare(FishingShopTO lhs, FishingShopTO rhs) {
			return collator.compare(lhs.getLetter(), rhs.getLetter());
		}
	}

	private class FishingShopAdapter extends BaseAdapter implements StickyListHeadersAdapter, SectionIndexer {

		@Override
		public int getCount() {
			return mShops == null ? 0 : mShops.size();
		}

		@Override
		public Object getItem(int position) {
			return mShops == null ? null : mShops.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(mContext, R.layout.menu_item, null);
			}
			TextView view = ViewHolder.get(convertView, R.id.text);
			view.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			FishingShopTO to = mShops.get(position);
			view.setText(to.getName());
			return convertView;
		}

		@Override
		public Object[] getSections() {
			return mSectionText;
		}

		@Override
		public int getPositionForSection(int section) {
			if (section >= mSectionPositions.length) {
				section = mSectionPositions.length - 1;
			} else if (section < 0) {
				section = 0;
			}
			return mSectionPositions[section];
		}

		@Override
		public int getSectionForPosition(int position) {
			for (int i = 0; i < mSectionPositions.length; i++) {
				if (position < mSectionPositions[i]) {
					return i - 1;
				}
			}
			return mSectionPositions.length - 1;
		}

		@Override
		public View getHeaderView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.menu_category_header, null);
			}
			TextView titleTxt = ViewHolder.get(convertView, R.id.text);
			int section = getSectionForPosition(position);
			if (section >= 0) {
				String sectionTxt = String.valueOf(getSections()[section]);
				titleTxt.setText(sectionTxt);
			}
			return convertView;
		}

		@Override
		public long getHeaderId(int position) {
			return getSectionForPosition(position);
		}
	}

}
